package server

import (
	"appengine"
	"appengine/datastore"
	"appengine/user"
	"fmt"
	"http"
	"log"
	"time"
)

func init() {
	http.HandleFunc("/upgrade", upgrade)
	http.HandleFunc("/upgradedone", upgradeDone)
}

func upgrade(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	u := user.Current(c)

	if r.Method == "GET" {
		k := datastore.NewKey(c, "Person", u.Id, 0, nil)
		var data struct {
			P          Person
			CompiledJS bool
		}
		data.CompiledJS = !appengine.IsDevAppServer()
		if err := datastore.Get(c, k, &data.P); err != nil {
			// ignore error, assume nonexistent user
			if err != datastore.ErrNoSuchEntity {
				log.Printf("upgrade non-fatal GET error: %v", err)
			}
		}
		if data.P.Email == "" {
			data.P.Email = u.Email
		}
		if err := htmlSet.Execute(w, "upgrade.html", data); err != nil {
			http.Error(w, err.String(), http.StatusInternalServerError)
		}
		return
	}
	if r.Method != "POST" {
		http.Error(w, "expect GET or POST", http.StatusInternalServerError)
		return
	}

	p := Person{
		ShortName: r.FormValue("shortname"),
		Email: r.FormValue("email"),
		SignupDate: time.UTC().Seconds(),
	}
	k := datastore.NewKey(c, "Person", u.Id, 0, nil)
	_, err := datastore.Put(c, k, &p)
	if err != nil {
		str := fmt.Sprintf("put Person: %s", err.String())
		http.Error(w, str, http.StatusInternalServerError)
		return
	}

	upgradeDone(w, r)
}

func upgradeDone(w http.ResponseWriter, r *http.Request) {
	if err := htmlSet.Execute(w, "upgradedone.html", nil); err != nil {
		http.Error(w, err.String(), http.StatusInternalServerError)
	}
}
